import { useRef, useState, useCallback } from "react";

export default function useSyncState(defaultValue) {
  const [, forceUpdate] = useState(0);

  const stateRef = useRef(typeof defaultValue === "function" ? defaultValue() : defaultValue);

  const setState = useCallback((action) => {
    stateRef.current = typeof action === "function" ? action(stateRef.current) : action;

    forceUpdate((prev) => prev + 1);
  }, []);

  const getState = useCallback(() => stateRef.current, []);

  return [stateRef.current, setState, getState];
}
